#!/usr/bin/env python #cauta interpretorul pentru ca aplicatia sa fie cross-platform

import wx  #importarea librariei grafice wxPython

class ToolbarFrame(wx.Frame): #clasa nou definita 'ToolarFrame' mostenste,sau este derivata din clasa wx.Frame care este clasa parinte

    def __init__(self, parent, id):   #constructorul clasei nou definite
        wx.Frame.__init__(self, parent, id, 'Calculator v.01',size=(250, 200)) #se apeleaza constructorul clasei parinte,wx.Frame
                                                                                        
        ########################## Meniul ##############################
        menubar=wx.MenuBar() #crearea unui obiect bara de meniu
        help=wx.Menu() #crearea unui obiect meniu
        help.Append(100,'&About') 
        self.Bind(wx.EVT_MENU,self.OnAboutBox,id=100) #activarea functiei handler OnAboutBox la activarea event-ului click pe meniul cu id-ul 100
        menubar.Append(help,'&Help') # adaugare la bara de meniu 'Help'cu parintele 'About'                               
        self.SetMenuBar(menubar) #construiesc bara de meniu

        #Intr-un Frame,widget-urile sunt dispuse ierarhizat folosind clase 'child' din clasa wx.Sizer
        #Ierarhia care se foloseste in acest frame este urmatoarea: wx.Panel,wx.BoxSizer,wx.GridSizer
        #Altfel spus,aceste clase ma ajuta sa asez cum vreau widget-urile in Frame
        #Imagineaza-ti niste 'blocuri' care contin alte 'blocuri'
        #http://wxpython.org/docs/api/wx.Sizer-class.html

        panel = wx.Panel(self) 
        panel.SetBackgroundColour('Blue')  #panel-ul va avea culoarea de fundal galbena 

        sizer = wx.BoxSizer(wx.VERTICAL)  #elementele vor fi dispuse pe verticala in acest 'bloc'

        #____________v
        #crearea unui obiect wx.ComboBox cu id=-1  
        #http://wxpython.org/docs/api/wx.ComboBox-class.html
        self.display = wx.ComboBox(self, -1) 

        #Adaugare ComboBox la BoxSizer; includ 'blocul' Combobox in 'blocul' Sizer 
        #Aici intervine din nou conceptul de mostenire: clasa wx.BoxSizer mosteneste clasa wx.Sizer
        #http://wxpython.org/docs/api/wx.Sizer-class.html ; http://wxpython.org/docs/api/wx.BoxSizer-class.html
        sizer.Add(self.display, 0, wx.EXPAND) 
       
  
        # [7][8][9][/]
        # [4][5][6][*]
        # [1][2][3][-]
        # [0][.][C][+]

        #Folosesc clasa wx.GridSizer pentru a dispune widget-urile sub forma de matrice
        #http://wxpython.org/docs/api/wx.GridSizer-class.html
        gsizer = wx.GridSizer(4, 4) # 4 linii,4 coloane
        for row in (("7", "8", "9", "/"),
                   ("4", "5", "6", "*"),
                   ("1", "2", "3", "-"),
                   ("0", ".", "C", "+")):  #pentru fiecare rand din matrice
            for label in row:  #pentru fiecare element al randului
                b = wx.Button(self, -1, label) #creez un obiect de tip buton care au ca parinte widget-ul cu id=-1
                gsizer.Add(b)  #fiecare buton il adaug la Grid
                self.Bind(wx.EVT_BUTTON, self.OnButton, b) #la executarea event-ului 'click' pe buton se apeleaza functia handler OnButton

        sizer.Add(gsizer, 1, wx.EXPAND) #adaug la Sizer si acest 'bloc' care contine matricea cu butoane,adica Grid-ul

        # [    =     ]
        b = wx.Button(self, -1, "=")  #adaug de asemenea un buton cu label-ul '='
        self.Bind(wx.EVT_BUTTON, self.OnButton, b) #ii atribui de asemenea o functie handler
        sizer.Add(b, 0, wx.EXPAND)  #adaug la sizer; wx.EXPAND 'largeste' la maxim acest buton 
        self.equal = b #memorez acest buton intr-o variabila

        # Set sizer and center
        self.SetSizer(sizer) #afisez tot ce am construit pana acum
        sizer.Fit(self)  #afisez la dimensiunile minime
        self.CenterOnScreen() #centrare pe ecran

        panel.SetSizer(sizer) #box-ul il adaug in panel
    
    def OnButton(self, evt):
        '''Handle button click event'''
        
        #Aflu ce buton am apasat
        label = evt.GetEventObject().GetLabel()

        if label == "=": #inseamna ca trebuie sa fac un calcul 
            try:
                compute = self.display.GetValue() #preiau expresia din CombBox
                # Ignore empty calculation
                if not compute.strip(): #daca prin inlaturarea spatiilor de la inceputul si sfarsitul sirului nu am vreun caracter
                    return         

                # Calculate result
                result = eval(compute)

                # Add to history
                self.display.Insert(compute, 0)
              
                # Show result
                self.display.SetValue(str(result))
            except Exception, e:
                wx.LogError(str(e))
                return

        elif label == "C": # Clear
            self.display.SetValue("")

        else: # Just add button text to current calculation 
            self.display.SetValue(self.display.GetValue() + label) 
            self.equal.SetFocus() # Set the [=] button in focus ; ca sa pot apasa = direct de la tastatura
    def OnAboutBox(self,event):

        description = """Calculator is a simple graphic user interface designed for doing simple mathematical calculas."""

        licence = """
             Calculator is free software; you can redistribute 
        it and/or modify it under the terms of the GNU General Public License as 
        published by the Free Software Foundation; either version 2 of the License, 
        or (at your option) any later version.

             Calculator is distributed in the hope that it will be useful, 
        but WITHOUT ANY WARRANTY; without even the implied warranty of 
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
             See the GNU General Public License for more details. You should have 
        received a copy of the GNU General Public License along with File Hunter; 
        if not, write to the Free Software Foundation, Inc., 59 Temple Place, 
        Suite 330, Boston, MA  02111-1307  USA"""

        info = wx.AboutDialogInfo()

        info.SetName('Calculator')
        info.SetVersion('1.0')
        info.SetDescription(description)
        info.SetCopyright('(C) 2012 Echipa D')
        info.SetWebSite('http://www.echipa-d.comuf.com')
        info.SetLicence(licence)
        info.AddDeveloper('http://pythonwise.blogspot.ro/') 
        info.AddDeveloper('http://zetcode.com/wxpython/') 
        info.AddDeveloper('Paun Florea')
        info.AddDeveloper('New Luca')
        

        wx.AboutBox(info)

             
    def OnCloseMe(self, event):
        self.Close(True)

    def OnCloseWindow(self, event):
        self.Destroy()

if __name__ == '__main__':
    app = wx.PySimpleApp()                    #obiectul de aplicatie,application object
    frame = ToolbarFrame(parent=None, id=-1)  #instanta obiect a clasei ToolbarFrame
    frame.Show()                              #afisarea obiectului
    app.MainLoop()                            #event loop-ul




